package com.leyou.user.controller;

import com.leyou.api.R;
import com.leyou.pojo.UserEntity;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


/**
 * 用户表
 *
 * @author Daifeng
 * @email 2661184062@qq.com
 * @date 2020-12-25 16:44:45
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 发送手机验证码
     * @param phone
     * @return
     */
    @PostMapping("/sendcode")
    public R sendVerifyCode(String phone) {
        Boolean boo = this.userService.sendcode(phone);
        if (boo == null) {
            return R.error().put("data",boo);
        }
        return R.ok().put("data",boo);

    }

    /**
     * 校验数据是否可用
     * @param data
     * @param type  1为用户名 2为手机号
     * @return
     */
    @GetMapping("/check/{data}/{type}")
    public R checkUserData(@PathVariable("data") String data,
                            @PathVariable(value = "type") Integer type) {
        Boolean boo = this.userService.checkData(data, type);
        if (boo == null) {
            return R.error().put("data",boo);
        }
        return R.ok().put("data",boo);

    }

    /**
     * 保存注册信息
     * @param user
     * @param result  数据校验
     * @return
     */
    @RequestMapping("/register")
    public R register(@Valid @RequestBody UserEntity user, BindingResult result){
        Map<String,String> map = new HashMap<>();
        if(result.hasErrors()){
            //1、获取校验的错误结果
            result.getFieldErrors().forEach((item)->{
                //FieldError 获取到错误提示
                String message = item.getDefaultMessage();
                //获取错误的属性的名字
                String field = item.getField();
                map.put(field,message);
            });
            return R.error(400,"提交的数据不合法").put("data",map);
        }else {
            Boolean flag = userService.register(user);
            if (!flag){
                map.put("403","验证码输入错误");
                return R.error().put("data",map);
            }
        }
        return R.ok();
    }

    /**
     * 根据用户名和密码查询用户
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public R queryUser(
            @RequestParam("username") String username,
            @RequestParam("password") String password) {
        UserEntity user = this.userService.queryUser(username, password);
        if (user == null) {
            return R.error();
        }
        return R.ok().put("data",user);
    }

}
